package xdu.ble.alarm.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import xdu.ble.alarm.config.YmlConfig;
import xdu.ble.alarm.entity.Alarm;
import xdu.ble.alarm.mapper.AlarmMapper;
import xdu.ble.common.enums.ExceptionCode;
import xdu.ble.common.exception.BLEException;

import java.util.Date;

/**
 * @Author com.alibaba.lizhen
 * @Date 2021/1/14 4:01 下午
 * @Version 1.0
 * @Description
 */
@Service
public class AlarmService {

    @Autowired
    private AlarmMapper alarmMapper;


    @Autowired
    private YmlConfig ymlConfig;

    private final Logger logger = LoggerFactory.getLogger(AlarmService.class);


    /**
     * 查询
     * @param alarmId
     * @return
     */
    public Alarm findAlarmById(String alarmId) {
        Example example = new Example(Alarm.class);
        example.createCriteria().andCondition("alarm_id = ", alarmId);
        return alarmMapper.selectOneByExample(example);
    }

    /**
     * 查询
     * @param nbDeviceId
     * @return
     */
    public Alarm findAlarmByNBDeviceId(String nbDeviceId) {
        Example example = new Example(Alarm.class);
        example.createCriteria().andCondition("nb_device_id = ", nbDeviceId);
        return alarmMapper.selectOneByExample(example);
    }
    /**
     * 激活
     * @return Result
     */
    public boolean activeAlarm(Alarm alarm) {
        alarm.setIsUsing("是");
        return this.updatePatientInfo(alarm);
    }

    /**
     * 解除警报
     * @param alarmId
     * @return
     */
    public boolean releaseAlarm(String alarmId){
        Alarm alarm = this.findAlarmById(alarmId);
        if (alarm == null) {
            throw new BLEException(ExceptionCode.ALARM_NOT_ACTIVE_OR_EXIST);
        }
        Example example = new Example(Alarm.class);
        example.createCriteria().andCondition("alarm_id = ", alarmId);
        alarm.setModifyTime(new Date());
        alarm.setIsWarn("否");
        //4 TODO 下发nb  直接下发nb链路可能不通
//        ClientUtils.sendToNbHttpPost(alarm.getNbDeviceId(),Integer.parseInt(alarm.getNbProductId()), NBCommandEnum.ALARM_CLEAR.getCommand());
        return alarmMapper.updateByExampleSelective(alarm, example) == 1;
    }
    /**
     * 修改报警器信息
     * @param alarm
     * @return
     */
    public boolean updatePatientInfo(Alarm alarm) {
        if (this.findAlarmById(alarm.getAlarmId()) == null) {
            throw new BLEException(ExceptionCode.ALARM_NOT_ACTIVE_OR_EXIST);
        }
        Example example = new Example(Alarm.class);
        example.createCriteria().andCondition("alarm_id = ", alarm.getAlarmId());
        alarm.setModifyTime(new Date());
        return alarmMapper.updateByExampleSelective(alarm, example) == 1;
    }

}
